import React, { useState, useEffect } from 'react';
import {
    Card, Table, Button, Space, Input, message,
    Popconfirm, Tag, Tooltip, Modal, Row, Col
} from 'antd';
import {
    PlusOutlined, DeleteOutlined, EditOutlined,
    UsergroupAddOutlined, SearchOutlined, InfoCircleOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import userGroupApi, { UserGroup } from '../../api/userGroup';
import UserGroupForm from '../../components/userGroup/UserGroupForm';
import './userGroup.scss';

const { Search } = Input;

const UserGroupPage: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [userGroups, setUserGroups] = useState<UserGroup[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [searchText, setSearchText] = useState<string>('');
    const [formVisible, setFormVisible] = useState<boolean>(false);
    const [editingGroup, setEditingGroup] = useState<UserGroup | null>(null);

    const navigate = useNavigate();

    // 加载用户组列表数据
    const fetchUserGroups = async () => {
        setLoading(true);
        try {
            const params = {
                page: currentPage,
                pageSize,
                name: searchText
            };

            const response = await userGroupApi.getUserGroups(params);

            if (response.success && response.data) {
                setUserGroups(response.data.groups);
                setTotal(response.data.total);
            } else {
                message.error(response.message || '获取用户组列表失败');
            }
        } catch (error) {
            console.error('获取用户组列表出错:', error);
            message.error('获取用户组列表失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 组件加载时获取数据
    useEffect(() => {
        fetchUserGroups();
    }, [currentPage, pageSize, searchText]);

    // 处理分页变化
    const handlePageChange = (page: number, size?: number) => {
        setCurrentPage(page);
        if (size) {
            setPageSize(size);
        }
    };

    // 处理搜索
    const handleSearch = (value: string) => {
        setSearchText(value);
        setCurrentPage(1); // 重置到第一页
    };

    // 处理删除用户组
    const handleDelete = async (id: string) => {
        try {
            const response = await userGroupApi.deleteUserGroup(id);

            if (response.success) {
                message.success('删除用户组成功');
                fetchUserGroups(); // 重新加载数据
            } else {
                message.error(response.message || '删除用户组失败');
            }
        } catch (error) {
            console.error('删除用户组出错:', error);
            message.error('删除用户组失败，请稍后重试');
        }
    };

    // 打开编辑表单
    const handleEdit = (group: UserGroup) => {
        setEditingGroup(group);
        setFormVisible(true);
    };

    // 查看用户组成员
    const handleViewMembers = (id: string) => {
        navigate(`/user-groups/${id}/members`);
    };

    // 创建或更新用户组
    const handleSave = async (values: any) => {
        try {
            let response;

            if (editingGroup) {
                // 更新已有用户组
                response = await userGroupApi.updateUserGroup(editingGroup.id, values);
            } else {
                // 创建新用户组
                response = await userGroupApi.createUserGroup(values);
            }

            if (response.success) {
                message.success(editingGroup ? '更新用户组成功' : '创建用户组成功');
                setFormVisible(false);
                setEditingGroup(null);
                fetchUserGroups(); // 重新加载数据
            } else {
                message.error(response.message || (editingGroup ? '更新用户组失败' : '创建用户组失败'));
            }
        } catch (error) {
            console.error(editingGroup ? '更新用户组出错:' : '创建用户组出错:', error);
            message.error(editingGroup ? '更新用户组失败，请稍后重试' : '创建用户组失败，请稍后重试');
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '用户组名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string, record: UserGroup) => (
                <Space>
                    {text}
                    {record.memberCount && record.memberCount > 0 && (
                        <Tag color="blue">{record.memberCount} 用户</Tag>
                    )}
                </Space>
            )
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
        },
        {
            title: '权限',
            dataIndex: 'permissions',
            key: 'permissions',
            render: (permissions: string[]) => (
                <Space size={[0, 4]} wrap>
                    {permissions && permissions.map((permission) => (
                        <Tag color="green" key={permission}>
                            {permission}
                        </Tag>
                    ))}
                </Space>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (text: string) => new Date(text).toLocaleString()
        },
        {
            title: '操作',
            key: 'action',
            width: 200,
            render: (_: any, record: UserGroup) => (
                <Space size="middle">
                    <Tooltip title="编辑">
                        <Button
                            type="text"
                            icon={<EditOutlined />}
                            onClick={() => handleEdit(record)}
                        />
                    </Tooltip>

                    <Tooltip title="查看成员">
                        <Button
                            type="text"
                            icon={<UsergroupAddOutlined />}
                            onClick={() => handleViewMembers(record.id)}
                        />
                    </Tooltip>

                    <Tooltip title="删除">
                        <Popconfirm
                            title="确定要删除此用户组吗？"
                            description="此操作不可逆，删除后组内的所有用户将失去该组的权限"
                            onConfirm={() => handleDelete(record.id)}
                            okText="是"
                            cancelText="否"
                        >
                            <Button
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                            />
                        </Popconfirm>
                    </Tooltip>
                </Space>
            )
        }
    ];

    return (
        <div className="user-group-page">
            <Card
                title={
                    <Space align="center">
                        <UsergroupAddOutlined />
                        <span>用户组管理</span>
                    </Space>
                }
                extra={
                    <Space>
                        <Search
                            placeholder="搜索用户组名称"
                            onSearch={handleSearch}
                            style={{ width: 250 }}
                            allowClear
                            prefix={<SearchOutlined />}
                        />
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => {
                                setEditingGroup(null);
                                setFormVisible(true);
                            }}
                        >
                            新建用户组
                        </Button>
                    </Space>
                }
            >
                <Table
                    dataSource={userGroups}
                    columns={columns}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        current: currentPage,
                        pageSize: pageSize,
                        total: total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        onChange: handlePageChange,
                        showTotal: (total) => `共 ${total} 条`
                    }}
                />
            </Card>

            {/* 编辑/创建用户组表单对话框 */}
            <Modal
                title={
                    <Space>
                        {editingGroup ? <EditOutlined /> : <PlusOutlined />}
                        <span>{editingGroup ? '编辑用户组' : '新建用户组'}</span>
                    </Space>
                }
                open={formVisible}
                onCancel={() => {
                    setFormVisible(false);
                    setEditingGroup(null);
                }}
                footer={null}
                destroyOnClose
                width={640}
            >
                <UserGroupForm
                    initialValues={editingGroup || undefined}
                    onFinish={handleSave}
                    onCancel={() => {
                        setFormVisible(false);
                        setEditingGroup(null);
                    }}
                />
            </Modal>
        </div>
    );
};

export default UserGroupPage; 